package com.hz.score.common.util;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hz.score.common.dto.PageDto;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

public class ConvertUtil {

    public static <D, M> D convert(M md, Class<D> dtoClass) {
        try {
            D dto = dtoClass.newInstance();
            BeanUtils.copyProperties(md, dto);
            return dto;
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static <D, M> PageDto<D> convertPage(Page<M> page, Class<D> dtoClass) {
        PageDto<D> pageDto = new PageDto<>();
        pageDto.setSize(page.getSize());
        pageDto.setTotal(page.getTotal());
        pageDto.setCurrent(page.getCurrent());
        List<D> recordsD = new ArrayList<>();
        pageDto.setRecords(recordsD);
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            page.getRecords().forEach(recordsM -> {
                D dto = null;
                try {
                    dto = dtoClass.newInstance();
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
                BeanUtils.copyProperties(recordsM, dto);
                recordsD.add(dto);
            });
        }
        return pageDto;
    }

    public static <D, M> List<D> convertList(List<M> mdList, Class<D> dtoClass) {
        List<D> dtoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(mdList)) {
            mdList.forEach(md -> {
                D dto = null;
                try {
                    dto = dtoClass.newInstance();
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
                BeanUtils.copyProperties(md, dto);
                dtoList.add(dto);
            });
        }
        return dtoList;
    }

    public static <D, M> D convert(M from, D to) {
        BeanUtils.copyProperties(from, to);
        return to;
    }

    public static <D, M> D convert(M from, D to, String[] ignoreArray) {
        BeanUtils.copyProperties(from, to, ignoreArray);
        return to;
    }
}
